package org.androidpn.server.xmpp.push;

import java.util.List;

import org.androidpn.server.entity.FriendMessage;
import org.androidpn.server.entity.Role;
import org.androidpn.server.service.FriendMessageService;
import org.androidpn.server.service.RoleService;
import org.androidpn.server.service.ServiceLocator;
import org.androidpn.server.xmpp.packet.FriendMessagePacket;
import org.androidpn.server.xmpp.packet.FriendMessagePacket.Operation;
import org.androidpn.server.xmpp.session.ClientSession;
import org.androidpn.server.xmpp.session.SessionManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.jivesoftware.smack.util.StringUtils;
import org.xmpp.packet.IQ;

/**
 * 推送好友信息线程
 * 
 * @author 蔡琪
 * 
 */
public class PushFriendMessageToClientThread implements Runnable {

	protected final Log log = LogFactory.getLog(getClass());

	private Long roleId;
	private SessionManager sessionManager;
	private FriendMessageService friendMessageService = null;
	private RoleService roleService = null;

	public PushFriendMessageToClientThread(Long roleId,
			SessionManager sessionManager) {
		this.roleId = roleId;
		this.sessionManager = sessionManager;
		friendMessageService = (FriendMessageService) ServiceLocator
				.getService(ServiceLocator.FRIEND_MESSAGE_SERVICE);
		roleService = (RoleService) ServiceLocator
				.getService(ServiceLocator.ROLE_SERVICE);
	}

	public void run() {
		Role role = roleService.find(roleId);
		if (role == null || !role.getIsOnline()) {
			return;
		}
		List<FriendMessage> friendMessages = friendMessageService
				.findFriendMessagesByReceiverId(roleId);
		if (friendMessages == null || friendMessages.isEmpty()) {
			return;
		}
		ClientSession clientSession = sessionManager.getSession(role.getUser()
				.getUsername());
		if (clientSession != null) {
			FriendMessagePacket friendMessagePacket = new FriendMessagePacket();
			friendMessagePacket.setFriendMessages(friendMessages);
			friendMessagePacket.setOperation(Operation.pushMessage);
			IQ iq = new IQ();
			iq.setID("PushFriendMessageToClient");
			iq.setTo(clientSession.getAddress());
			if (friendMessagePacket.getChildElementXML() != null) {
				Document doc;
				try {
					doc = DocumentHelper.parseText(friendMessagePacket
							.getChildElementXML());
					System.out.println("PushFriendMessageToClient="
							+ StringUtils.unescapeNode(friendMessagePacket
									.getChildElementXML()));
					Element element = doc.getRootElement();
					iq.setChildElement(element.createCopy());
					iq.setType(IQ.Type.result);
					clientSession.process(iq);
					friendMessageService.sendDone(friendMessages);
				} catch (DocumentException e) {
					e.printStackTrace();
				}
			}
		}
	}
}